package com.xiaoyun.controller;

import com.xiaoyun.enums.OperatorFriendRequestTypeEnum;
import com.xiaoyun.enums.SearchFriendsStatusEnum;
import com.xiaoyun.pojo.ChatMsg;
import com.xiaoyun.pojo.vo.MyFriendsVO;
import com.xiaoyun.service.strategy.manage.IOperFriendManage;
import com.xiaoyun.pojo.Users;
import com.xiaoyun.pojo.bo.OperFriendBO;
import com.xiaoyun.pojo.bo.UserSearchBO;
import com.xiaoyun.pojo.bo.UsersBO;
import com.xiaoyun.pojo.group.EditNickname;
import com.xiaoyun.pojo.group.UploadImg;
import com.xiaoyun.pojo.vo.UsersVO;
import com.xiaoyun.service.UserService;
import com.xiaoyun.utils.FastDFSClient;
import com.xiaoyun.utils.FileUtils;
import com.xiaoyun.utils.IMoocJSONResult;
import com.xiaoyun.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.List;


@RestController
@RequestMapping("u")
@Slf4j
public class UserController {


    private final UserService userService;

    private final FastDFSClient fastDFSClient;

    private final IOperFriendManage iOperFriendManage;

    @Autowired
    public UserController(UserService userService, FastDFSClient fastDFSClient, IOperFriendManage iOperFriendManage) {
        this.userService = userService;
        this.fastDFSClient = fastDFSClient;
        this.iOperFriendManage = iOperFriendManage;
    }

    @PostMapping("/registOrLogin")
    public IMoocJSONResult registOrLogin(@RequestBody @Validated Users user) throws Exception {
        boolean usernameIsExist = userService.queryUsernameIsExist(user.getUsername());
        Users userResult = null;
        if (usernameIsExist) {
            userResult = userService.queryUserForLogin(user.getUsername(),
                    MD5Utils.getMD5Str(user.getPassword()));
            if (userResult == null) {
                return IMoocJSONResult.errorMap("用户名或者密码不正确");
            }
        } else {
            user.setNickname(user.getUsername());
            user.setFaceImage("");
            user.setFaceImageBig("");
            user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
            userResult = userService.saveUser(user);
        }
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(userResult, usersVO);
        return IMoocJSONResult.ok(usersVO);
    }

    @PostMapping("/uploadFaceBase64")
    public IMoocJSONResult uploadFaceBase64(@RequestBody @Validated({UploadImg.class}) UsersBO usersBO) throws Exception {
        String base64Data = usersBO.getFaceData();
        String userFacePath = "F:\\" + usersBO.getUserId() + "userface64.png";
        FileUtils.base64ToFile(userFacePath, base64Data);
        MultipartFile faceFile = FileUtils.fileToMultipart(userFacePath);
        String url = fastDFSClient.uploadBase64(faceFile);
        log.info("url:{}", url);

        String thumpImgUrl = url.replace(".png", "_80x80.png");

        Users user = new Users();
        user.setId(usersBO.getUserId());
        user.setFaceImage(thumpImgUrl);
        user.setFaceImageBig(url);
        return IMoocJSONResult.ok(user);
    }

    @PostMapping("/setNickname")
    public IMoocJSONResult setNickname(@RequestBody @Validated({EditNickname.class}) UsersBO usersBO) throws Exception {
        Users users = new Users();
        users.setId(usersBO.getUserId());
        users.setNickname(usersBO.getNickname());
        Users result = userService.updateUserInfo(users);
        return IMoocJSONResult.ok(result);
    }

    /**
     * 根据账号做匹配查询
     *
     * @param userSearchBO
     * @return
     */
    @PostMapping("/search")
    public IMoocJSONResult searchUser(@Validated UserSearchBO userSearchBO) {
        SearchFriendsStatusEnum searchStatus = userService.preconditionSearchFriends(userSearchBO);
        if (searchStatus == SearchFriendsStatusEnum.SUCCESS) {
            Users users = userService.queryUserInfoByUsername(userSearchBO.getFriendUsername());
            UsersVO usersVO = new UsersVO();
            BeanUtils.copyProperties(users, usersVO);
            return IMoocJSONResult.ok(usersVO);
        } else {
            return IMoocJSONResult.errorMsg(searchStatus.msg);
        }
    }

    @PostMapping("/addFriendRequest")
    public IMoocJSONResult addFriendRequest(@Validated UserSearchBO userSearchBO) {
        SearchFriendsStatusEnum searchStatus = userService.preconditionSearchFriends(userSearchBO);
        if (searchStatus == SearchFriendsStatusEnum.SUCCESS) {
            userService.sendFriendRequest(userSearchBO);
            return IMoocJSONResult.ok();
        } else {
            return IMoocJSONResult.errorMsg(searchStatus.msg);
        }
    }

    @PostMapping("/queryFriendRequests")
    public IMoocJSONResult queryFriendRequests(String userId) {
        if (StringUtils.isBlank(userId)) {
            return IMoocJSONResult.errorMsg("");
        } else {
            return IMoocJSONResult.ok(userService.queryFriendRequestList(userId));
        }
    }

    @PostMapping("/operFriendRequest")
    public IMoocJSONResult operFriendRequest(@Validated OperFriendBO operFriendBO) {
        Integer openType = operFriendBO.getOperType();
        if (StringUtils.isBlank(OperatorFriendRequestTypeEnum.getMsgByType(openType))) {
            return IMoocJSONResult.errorMap("");
        }
        String sendUserId = operFriendBO.getSendUserId();
        String acceptUserId = operFriendBO.getAcceptUserId();

        iOperFriendManage.exec(openType, sendUserId, acceptUserId);

        List<MyFriendsVO> list = userService.queryMyFriend(acceptUserId);

        return IMoocJSONResult.ok(list);
    }

    @PostMapping("/myFriend")
    public IMoocJSONResult myFriends(String userId) {
        if (StringUtils.isBlank(userId)) {
            return IMoocJSONResult.errorMap("");
        }
        List<MyFriendsVO> list = userService.queryMyFriend(userId);

        return IMoocJSONResult.ok(list);
    }

    @PostMapping("/getUnReadMsgList")
    public IMoocJSONResult getUnReadMsgList(String acceptUserId) {
        if (StringUtils.isBlank(acceptUserId)) {
            return IMoocJSONResult.errorMap("");
        }
        List<ChatMsg> list = userService.getUnReadMsgList(acceptUserId);
        return IMoocJSONResult.ok(list);
    }
}
